<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use App\Http\Requests\Api\V1\UserAddressRequest;

use App\Models\UserAddress;
use Cblink\Region\Region;

use App\Http\Resources\V1\UserAddressResource;

class UserAddressesController extends Controller
{
    public function index(Request $request)
    {
        return UserAddressResource::collection($request->user()->addresses);
    }

    public function show(UserAddress $address, Request $request)
    {
        return new UserAddressResource($address);
    }

    public function default(Request $request)
    {
        $address = $request->user()->addresses()->orderByUseTime()->first();

        if($address){
            return new UserAddressResource($address);
        }else{
            return response(null, 200);
        }
    }

    public function store(UserAddressRequest $request, Region $region)
    {
        $filler = $request->only(['address', 'contact_name', 'contact_phone', 'city', 'province', 'district']);

        $address = $request->user()->addresses()->create($filler);

        return new UserAddressResource($address);
    }

    public function update(UserAddress $address, Request $request, Region $region)
    {
        $filler = $request->only(['address', 'contact_name', 'contact_phone', 'city', 'province', 'district']);

        $address->update($filler);

        return new UserAddressResource($address);
    }

    public function delete(UserAddress $address, Request $request)
    {
        $address->delete();

        return response(null, 201);
    }

    protected function _getRegion($id, Region $region)
    {
        $parents = $region->nestFromChild($id)->first();

        $address['district'] = $parents->name;
        $address['district_id'] = $parents->id;
        $address['zip'] = $parents->code;
        $address['city'] = $parents->parent->name;
        $address['city_id'] = $parents->parent->id;
        $address['province'] = $parents->parent->parent->name;
        $address['province_id'] = $parents->parent->parent->id;

        return $address;
    }
}
